//
//  MNDRiskAssessWebViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/11/8.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDRiskAssessWebViewController.h"
#import "SYWebLoadingProgress.h"
#import "MNDLoginUserModel.h"
#import "RSAUtil.h"

@interface MNDRiskAssessWebViewController ()<UIWebViewDelegate>

@property (strong, nonatomic) SYWebLoadingProgress *webLoadingProgress;
@property (nonatomic, strong) UIWebView *webView;

@end

@implementation MNDRiskAssessWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialWebView];
    
    [self initialLeftBarButtonItem];
}

- (void)initialLeftBarButtonItem {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    UIViewController *viewController = self.navigationController.viewControllers[self.indexOfViewController];
    [self.navigationController popToViewController:viewController animated:YES];
}

- (SYWebLoadingProgress *)webLoadingProgress {
    if (!_webLoadingProgress) {
        _webLoadingProgress = [[SYWebLoadingProgress alloc] init];
        _webLoadingProgress.progressColor = kColorBlue;
        _webLoadingProgress.progressStyle = LoadingPregressType_Noraml;
    }
    
    if ([self.navigationController.navigationBar isHidden]) {
        _webLoadingProgress.frame = CGRectMake(0, 20, kScreenWidth, 2);
        
    } else {
        CGFloat yPosition = 64.0;
        if (kScreenHeight >= 812) {
            yPosition = 88;
        }
        _webLoadingProgress.frame = CGRectMake(0, yPosition, kScreenWidth, 2);
        //        [self.view.layer insertSublayer:_webLoadingProgress atIndex:0];
    }
    [self.webView.layer addSublayer:_webLoadingProgress];
    
    return _webLoadingProgress;
}

- (void) initialWebView {
    
    self.webView = [[UIWebView alloc] init];
    self.webView.backgroundColor = kColorBackground;
    self.webView.scrollView.bounces = NO;
    //    self.webView.detectsPhoneNumbers = NO;
    
    [self.view addSubview:self.webView];
    //    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.edges.equalTo(self.view);
    //    }];
    self.webView.scalesPageToFit = YES;
    
    self.webView.delegate = self;
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", BroswerHeadURL, [NSString urlEncodeStr:self.webViewUrl]];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSURLRequest *request = [self configRequestHeaderFileds:url];
    [self.webView loadRequest:request];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    //    [self.view beginLoading];
//    [self setCookies];
}

- (NSMutableURLRequest *)configRequestHeaderFileds: (NSURL *)url {
    // 添加请求头信息
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    NSString *userCode = [self rsaEncode: user.user_code];
    
    [request setValue:userCode forHTTPHeaderField:@"USERCODE"];
    
    return request;
}

- (NSString *)rsaEncode:(NSString *)rsaStr {
    NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", rsaStr] publicKey:RSA_PUBLIC_KEY];
    NSString *unreserved = @"";
    NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
    [allowed addCharactersInString:unreserved];
    
    NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
    
    return encodeEncryText;
}

- (NSMutableURLRequest *)addHTTPHeaderFieldWithRequest:(NSURLRequest *)request {
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    //来源加入header
    if (kDevice_iPad) {
        [mutableRequest addValue:@"iPad" forHTTPHeaderField:@"WERTYUIOP"];
    } else {
        [mutableRequest addValue:@"iPhone" forHTTPHeaderField:@"WERTYUIOP"];
    }
    
    return mutableRequest;
}

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSMutableURLRequest *mutableRequest = [self addHTTPHeaderFieldWithRequest:request];
    request = [mutableRequest copy];
    
    NSString *absouteStr = request.URL.absoluteString;
    NSLog(@"absouteStr : %@", absouteStr);
    if ([absouteStr isEqualToString:@"app://invest_test/go_app"]) {//前往投资
        self.tabBarController.selectedIndex = 1;
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [self.webLoadingProgress startProgressAnimation];
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    [self.webLoadingProgress completedProgressAnimation];
    //    取消长按webView上的链接弹出actionSheet的问题
    [webView stringByEvaluatingJavaScriptFromString: @"document.documentElement.style.webkitUserSelect='none';"];
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('nav-final')[0].style.display='none';"];
    //
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    //    [self.view endLoading];
    NSLog(@"error: %@", error);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setCookies {
    if ([MNDLoginUserModel isUserLogin]) {
        //        [self clearWebViewCookies];
        
        MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
        
        NSDictionary *dictCookieUId;
        
//        if ([userDict objectForKey:@"encode_user_code"]) {
//            dictCookieUId = @{NSHTTPCookieName: @"mobile_user_code",
//                              NSHTTPCookieValue: userDict[@"encode_user_code"],
//                              NSHTTPCookiePath: @"/",
//                              NSHTTPCookieVersion: @"0",
//                              NSHTTPCookieDomain: @".miniwangdai.com"
//                              };
//        } else {
            dictCookieUId = @{NSHTTPCookieName: @"user_code",
                              NSHTTPCookieValue: user.user_code,
                              NSHTTPCookiePath: @"/",
                              NSHTTPCookieVersion: @"0",
                              NSHTTPCookieDomain: @".miniwangdai.com"
                              };
//        }
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:dictCookieUId];
        
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
